# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# AmosERP odoo11.0
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'odoo'
# 公司网址： www.odoo.pw  www.100china.cn www.amoserp.com
# Copyright 昆山一百计算机有限公司 2012-2020 Amos
# 日期：2019/11/14
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.exceptions import AccessError, UserError, ValidationError
from ding_client import Client
from dingtalk import SecretClient, AppKeyClient


class ding_hr_department_wizard(models.TransientModel):
    _name = 'ding.hr.department.wizard'
    _description = u'下载同步部门'

    company_id = fields.Many2one('res.company', string=u'公司', index=True, default=lambda self: self.env.user.company_id)
    createdeptgroup = fields.Boolean(u"创建部门群,", default=False, help=u'是否同步创建一个关联此部门的企业群, true表示是, false表示不是')
    autoadduser = fields.Boolean(u"部门新人自动加入该群,", default=False, help=u'当群已经创建后，是否有新人加入部门会自动加入该群, true表示是, false表示不是')

    def get_department_ids(self, client, proced=set(), parent_id=None):

        ret = set()
        if parent_id is None:
            scopes = client.user.auth_scopes()
            parent_id = scopes.get('auth_org_scopes', {}).get('authed_dept', [])

        if isinstance(parent_id, (list, tuple)):
            for pid in parent_id:
                ret.update(self.get_department_ids(client, proced, pid))
            return ret

        if parent_id in proced:
            return ret
        ret.add(parent_id)
        ids = client.department.list_ids(parent_id)
        proced.add(parent_id)
        ret.update(set(ids))
        for _id in ids:
            ret.update(self.get_department_ids(client, proced, _id))

        return ret

    def print_user_list(self, client, department, parent_id):
        parent_department_name = self.env['hr.department'].browse(parent_id).display_name
        # 打印人员列表
        if not parent_department_name:
            department_name = department.name
        else:
            department_name = parent_department_name + '/' + department.name
        res = client.user.list(department.id)
        for useritem in res.userlist:
            print('部门：%s，职位：%s，姓名：%s' % (department_name, useritem.position, useritem.name))

    def but_yes(self):

        ding = self.env['res.ding'].search([('company_id', '=', int(self._context['company_id']))], order="id desc",
                                           limit=1)

        client = AppKeyClient(ding.corp_id, ding.app_key, ding.app_secret)

        if client:
            department1 = client.department.list()

            for d1 in department1:
                #::::当前一级部门
                parent_id1 = self.add_department(client, d1,False)
                #:::当前二级部门
                for d2 in client.department.list_ids(d1.id):
                    department = client.department.get(d2)
                    parent_id2 = self.add_department(client, department, parent_id1)
                    #:::当前三级部门
                    for d3 in client.department.list_ids(d2):
                        department = client.department.get(d3)
                        parent_id3 = self.add_department(client, department, parent_id2)
                        #:::当前四级部门
                        for d4 in client.department.list_ids(d3):
                            department = client.department.get(d4)
                            parent_id4 = self.add_department(client, department, parent_id3)
            return True


    def add_department(self, client, department, parent_id):
        self.print_user_list(client, department, parent_id)
        obj = self.env['hr.department']
        parm = {
            'name': department.name,
            'ding_createdeptgroup': department.createDeptGroup,
            'ding_autoadduser': department.autoAddUser,
            'ding_id': department.id,
            'ding_parentid': department.ding_parentid,
            'parent_id': parent_id,
            'company_id': int(self._context['company_id']),
        }
        if self._context['createdeptgroup']:
            parm['createdeptgroup'] = True
        if self._context['autoadduser']:
            parm['autoadduser'] = True
        #:::::如果存在更新不存在创建
        # records = obj.sudo().search([('ding_id', '=', o.id), ('company_id', '=', int(self._context['company_id']))], limit=1)
        records = obj.sudo().search([('name', '=', department.name), ('company_id', '=', int(self._context['company_id']))], limit=1)

        if records:
            records.write(parm)
            # records.action_department_user()
        else:
            records = obj.create(parm)
            # records.action_department_user()
        return records.id
